import React, { Component } from "react";
import QueueAnim from "rc-queue-anim";
import { connect } from "dva";
import { Table, Modal, Input, message, Form, Checkbox } from "antd";
import TagSelect from "@/components/TagSelect/TagSelect";
import AllContentTab from "@/components/DetailTabs/AllContentTab";
import { getCityTableContent, removeCityContent, getContentDetails, PushDraftList, PushDraft, getDetailesStatisticalData } from "../../services/services";
import "./City.less";

const { Search, TextArea } = Input;
@connect(({ add }) => ({ add: add }))
@Form.create()
class List extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showSiteVisible: false, //显示推稿站点变量
      showPushExplainVisible: false, //显示推稿说明变量
      create_time: "1970-01-01 00:00:00", //初始查询全部时间
      pageSize: 10, //表格数据当前页显示条数
      total: 0, //表格数据总条数
      currentPage: 1, //表格数据当前页码
      category: "文章", //分类名称
      categoryId: 1, //分类id
      keyword: "", //搜索关键词
      site_name: "", //站点名称
      searchType: 1, //搜索类型
      tableLoading: false, //表格加载效果
      tableData: [], //表格数据
      showDetailVariable: true, //显示详情页变量
      deleteExplainVisible: false, //删除对话框变量
      tabKey: "1", //详情tab页索引
      site_id: 0, //当前站点id
      article_ids: [], //文章id数组
      singleDeleteNote: "", //单一删除的说明
      currentIndex: -1, //当前站点的索引,
      siteList: [], //选取的要推送的列表
      selectedSiteList: [], //选取的要推送的列表
      pushNote: "", //推送说明
      currentRow: null, //当前行的数据
      statisticalData: [] //统计数据
    };
  }
  componentDidMount() {
    this.getTableData();
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (nextProps.match.params.List !== this.props.match.params.List) {
      this.setState(
        {
          site_id: Number(nextProps.match.params.List),
          showDetailVariable: true
        },
        () => {
          this.getTableData();
        }
      );
    }
    return true;
  }
  // 类别切换
  categoryChange = data => {
    this.setState(
      {
        tableLoading: true,
        keyword: "",
        category: data.category_name,
        categoryId: data.category_id
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 时间选择切换
  selectedTimeChange = timer => {
    this.setState(
      {
        tableLoading: true,
        create_time: timer
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 搜索
  handleSeachButton = data => {
    this.setState(
      {
        tableLoading: true,
        categoryId: data.category_id,
        keyword: data.searchKeyword,
        searchType: data.searchType,
        category: data.category_name
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 获取表格数据
  getTableData = () => {
    this.setState({
      tableLoading: true
    });
    const { categoryId, category, searchType, currentPage, pageSize, create_time, keyword } = this.state;
    const params = {
      content_type: categoryId,
      create_time: create_time,
      keyword: keyword,
      search_type: searchType,
      page: currentPage,
      per_page: pageSize,
      site_id: this.state.site_id || Number(this.props.match.params.List)
    };
    getCityTableContent(params)
      .then(res => {
        if (res.code === 200) {
          let siteNameList = JSON.parse(sessionStorage.getItem("BreadcrumbList"));
          let site_name = siteNameList[siteNameList.length - 1];
          const result = res.data;
          result.data.forEach((item, i) => {
            item.category = category;
            item.site_name = site_name;
            item.key = i;
            return item;
          });
          this.setState({
            tableLoading: false,
            total: result.total,
            currentPage: result.current_page,
            pageSize: result.per_page,
            tableData: result.data
          });
        } else {
          this.setState({
            tableLoading: false
          });
          message.error("");
        }
      })
      .catch(err => {
        this.setState({
          tableLoading: false
        });
        console.log(err);
      });
  };
  // 删除表格数据
  deleteTableContent = params => {
    removeCityContent(params)
      .then(res => {
        if (res.code === 200) {
          this.setState(
            {
              tableLoading: true
            },
            () => {
              this.getTableData();
            }
          );
        } else {
          message.error("");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 获取详情数据
  getDetailsData = contentId => {
    const params = {
      site_id: Number(this.props.match.params.List),
      content_type: this.state.categoryId,
      content_id: contentId
    };
    getContentDetails(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            detailsContent: res.data || {}
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 表格显示条数切换
  pageSizeChange = (current, size) => {
    this.setState(
      {
        pageSize: size,
        currentPage: current
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 当前页面变化
  currentPageChange = (page, pageSize) => {
    this.setState(
      {
        currentPage: page
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 跳转值详情
  showDetailChange = row => {
    this.setState(
      {
        showDetailVariable: false
      },
      () => {
        this.getDetailsData(row.id);
        this.getStatistical(row);
      }
    );
  };
  // 显示站点选择对话框
  showSiteModule = row => {
    this.getSiteList();
    this.setState({
      showSiteVisible: true,
      currentRow: row
    });
  };
  // 获取推送站点列表
  getSiteList = () => {
    const params = {
      site_id: Number(this.props.match.params.List)
    };
    PushDraftList(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            siteList: res.data
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 点击站点选择对话框取消
  handleSiteCancle = () => {
    this.setState({
      showSiteVisible: false,
      selectedSiteList: []
    });
  };
  // 点击站点选择对话框下一步
  nextStepChange = () => {
    this.setState({
      showSiteVisible: false,
      showPushExplainVisible: true
    });
  };
  // 选择推稿说明对话框上一步
  prepStepChange = () => {
    this.setState({
      showSiteVisible: true,
      showPushExplainVisible: false
    });
  };
  // 点击推稿说明对话框确定
  handlePushExplainOk = () => {
    this.handlePushDraft();
    this.setState({
      showPushExplainVisible: false
    });
  };
  // 推送稿件
  handlePushDraft = () => {
    if (this.state.selectedSiteList.length < 1) {
      this.setState({
        showSiteVisible: true
      });
      return message.error("推送站点不能为空");
    }
    this.props.form.validateFields(["pushNote"], (err, values) => {
      if (!err) {
        let receiveSite = [];
        this.state.selectedSiteList.forEach(item => {
          receiveSite.push(item.site_id);
        });
        const params = {
          site_id: Number(this.props.match.params.List),
          content_type: this.state.categoryId,
          content_id: this.state.currentRow.id,
          receive_site: receiveSite,
          push_notes: values.pushNote
        };
        PushDraft(params)
          .then(res => {
            if (res.code === 200) {
              message.success("推送成功");
              this.setState({
                selectedSiteList: []
              });
              this.props.form.setFieldsValue({ "pushNote": "" });
            } else if (res.code === 500) {
              this.setState({
                selectedSiteList: []
              });
              this.props.form.setFieldsValue({ "pushNote": "" });
              message.error("推送失败");
            } else {
              this.setState({
                selectedSiteList: []
              });
              this.props.form.setFieldsValue({ "pushNote": "" });
              console.log("连接失败");
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    });
  };
  // 显示删稿说明对话框
  showdeleteExplainModel = record => {
    let articleId = [];
    articleId.push(record.id);
    this.setState({
      deleteExplainVisible: true,
      article_ids: articleId
    });
  };
  // 点击删稿说明对话框确定
  deleteExplainModalOk = () => {
    const { site_id, categoryId, article_ids } = this.state;
    this.props.form.validateFields(["singleDeleteNote"], (err, values) => {
      if (!err) {
        const params = {
          site_id: Number(this.props.match.params.List),
          content_type: categoryId,
          content_id: article_ids,
          notes: values.singleDeleteNote
        };
        this.deleteTableContent(params);
        this.setState({
          deleteExplainVisible: false
        });
      }
    });
  };
  // 点击删稿说明对话框取消
  deleteExplainModalCancle = () => {
    this.props.form.resetFields();
    this.setState({
      deleteExplainVisible: false
    });
  };
  // 显示删稿说明对话框
  showdeleteExplainModel = record => {
    let articleId = [];
    articleId.push(record.id);
    this.setState({
      deleteExplainVisible: true,
      article_ids: articleId
    });
  };
  // 表格数据多选框的变化
  onTableSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      article_ids: selectedRowKeys
    });
  };
  // 批量删除
  deleteAllContentFun = allDeleteNote => {
    const { site_id, categoryId, article_ids } = this.state;
    const params = {
      site_id,
      content_type: categoryId,
      content_id: article_ids,
      notes: allDeleteNote
    };
    this.deleteTableContent(params);
    this.setState({
      deleteExplainVisible: false
    });
  };
  // 选取当前站点
  setCurrentSite = row => {
    const { selectedSiteList } = this.state;
    let nextSelectedsiteList = selectedSiteList.some(item => {
      return item.site_id === row.site_id;
    })
      ? [...selectedSiteList]
      : [...selectedSiteList, row];
    this.setState({
      selectedSiteList: nextSelectedsiteList
    });
  };
  // 选取所有站点
  setAllSite = e => {
    if (e.target.checked) {
      this.setState({
        selectedSiteList: this.state.siteList
      });
    } else {
      this.setState({
        selectedSiteList: []
      });
    }
  };
  // 获取选取站点的索引
  setCurrentIndex = event => {
    this.setState({
      currentIndex: parseInt(event.currentTarget.getAttribute("index"), 10)
    });
  };
  // 返回上一级
  goBack = () => {
    this.setState(
      {
        showDetailVariable: true
      },
      () => {
        // this.getTableData();
      }
    );
  };
  // 一键删除后返回上级
  handleDel = flag => {
    this.setState(
      {
        showDetailVariable: flag
      },
      () => {
        // this.getTableData();
      }
    );
  };
  // 获取详情统计数据
  getStatistical = row => {
    const params = {
      site_id: Number(this.props.match.params.List),
      content_type: this.state.categoryId,
      content_id: row.id,
      source: 1
    };
    getDetailesStatisticalData(params)
      .then(res => {
        if (res.code === 200) {
          let sdata = [];
          let arr = ["阅读量", "评论量", "点赞量", "分享量"];
          let arr1 = ["scan_count", "comment_count", "like_count", "share_count"];
          for (let i = 0; i < 4; i++) {
            let obj = {};
            obj["x"] = arr[i];
            obj["y"] = res.data[arr1[i]];
            sdata.push(obj);
          }
          this.setState({
            statisticalData: sdata
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 站点搜索
  searchSite = value => {
    if (value.trim() === "") {
      this.getSiteList();
    } else {
      let arr = this.state.siteList.filter(item => {
        if (item.site_name.indexOf(value) > -1) {
          return item;
        }
      });
      this.setState({
        siteList: arr
      });
    }
  };
  render() {
    const { tableData, total, tableLoading, selectedSiteList, siteList } = this.state;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: "标题",
        dataIndex: "title",
        key: "title",
        align: "center",
        width: "40%"
      },
      {
        title: "类型",
        dataIndex: "category",
        key: "category",
        align: "center"
      },
      {
        title: "发布站点",
        dataIndex: "site_name",
        key: "site_name",
        align: "center"
      },
      {
        title: "发布人",
        dataIndex: "create_user",
        key: "create_user",
        align: "center"
      },
      {
        title: "推送时间",
        dataIndex: "create_time",
        key: "create_time",
        align: "center"
      },
      {
        title: "操作",
        key: "is_delete",
        align: "center",
        render: (text, record) => {
          return (
            <div style={{ marginRight: "10%", textAlign: "right" }}>
              {this.props.add.rightList.indexOf("/supervise/button/push") > -1 ? (
                <span style={{ cursor: "pointer", color: "#1890ff" }} onClick={this.showSiteModule.bind(this, record)}>
                  推稿&nbsp;&nbsp;
                </span>
              ) : null}
              {this.props.add.rightList.indexOf("/supervise/button/delete") > -1 ? (
                <span>
                  {record.is_delete === 0 ? (
                    <span style={{ cursor: "pointer", color: "#1890ff" }} onClick={this.showdeleteExplainModel.bind(this, record)}>
                      &nbsp;&nbsp; 删除&nbsp;&nbsp;
                    </span>
                  ) : (
                    <span>已删除&nbsp;&nbsp;</span>
                  )}
                </span>
              ) : null}

              <span style={{ cursor: "pointer", color: "#1890ff" }} onClick={this.showDetailChange.bind(this, record)}>
                查看详情
              </span>
            </div>
          );
        }
      }
    ];
    // 表格分页器配置项
    const paginationProps = {
      current: this.state.currentPage,
      showSizeChanger: true,
      showQuickJumper: true,
      total: total,
      showTotal: () => `共 ${this.state.total} 条记录`,
      pageSize: this.state.pageSize,
      pageSizeOptions: ["5", "10", "20", "50"],
      onChange: this.currentPageChange,
      onShowSizeChange: this.pageSizeChange
    };
    const rowSelection = {
      onChange: this.onTableSelectChange
    };
    return (
      <QueueAnim className="List">
        <div key="t2" className="BasicContent">
          <div className="main">
            {this.state.showDetailVariable ? (
              <div>
                <TagSelect
                  currentCategory={[this.state.category]}
                  showAllDeleteModal={this.showdeleteExplainModel}
                  showAllDelVariable={this.props.add.rightList.indexOf("/supervise/button/delete") > -1 ? true : false}
                  getcategoryChange={this.categoryChange}
                  getSelectedTimeChange={this.selectedTimeChange}
                  handleSeachButton={this.handleSeachButton}
                  deleteAllContent={this.deleteAllContentFun}
                />
                <Table loading={tableLoading} rowKey={recored => recored.id} rowSelection={rowSelection} columns={columns} dataSource={tableData} bordered pagination={paginationProps} />
              </div>
            ) : (
              <div>
                {this.state.detailsContent ? (
                  <AllContentTab
                    statisticalData={this.state.statisticalData}
                    site_id={this.props.match.params.List}
                    refresh={this.handleDel}
                    categoryId={this.state.categoryId}
                    parentBack={this.goBack}
                    contentData={this.state.detailsContent}
                    tabKey={this.state.tabKey}
                  />
                ) : null}
              </div>
            )}
          </div>
          <Modal
            title={"选择站点"}
            width="600px"
            bodyStyle={{ height: 400, overflow: "hidden", display: "flex", backgroundColor: "#eaeaea" }}
            visible={this.state.showSiteVisible}
            onCancel={this.handleSiteCancle}
            okText="下一步"
            cancelText="取消"
            onOk={this.nextStepChange}
          >
            <div className="site-model-left">
              <Search placeholder="搜索站点名称" onSearch={this.searchSite} style={{ width: 280 }} />
              {siteList.length ? (
                <div style={{ padding: 5 }}>
                  <Checkbox onChange={this.setAllSite}>全选</Checkbox>
                </div>
              ) : null}
              <ul className="site-model-left-container">
                {siteList.length &&
                  siteList.map((item, i) => {
                    return (
                      <li index={i} onClick={this.setCurrentIndex} className={this.state.currentIndex === i ? "active" : ""} key={item.site_id}>
                        {item.site_name}
                        {this.state.currentIndex === i ? (
                          <span key={item.site_id} className="text" onClick={this.setCurrentSite.bind(this, item)}>
                            选取
                          </span>
                        ) : null}
                      </li>
                    );
                  })}
              </ul>
            </div>
            <div className="site-model-right">
              <div className="site-model-right-container">
                <h5 className="site-model-right-container-title">已选择{selectedSiteList.length}个站点</h5>
                {selectedSiteList.map(item => {
                  return <p key={item.site_id}>{item.site_name}</p>;
                })}
              </div>
            </div>
          </Modal>
          <Modal title="推送说明" visible={this.state.showPushExplainVisible} onCancel={this.prepStepChange} okText="提交" cancelText="上一步" onOk={this.handlePushExplainOk}>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item>
                {getFieldDecorator("pushNote", {
                  rules: [
                    { required: true, message: "请输入推送说明!" },
                    { whitespace: true, message: "不能输入空字符!" },
                    { max: 300, message: "不能大于300个字符" }
                  ]
                })(<TextArea placeholder="请输入300字以内的说明。。。" allowClear rows={6} />)}
              </Form.Item>
            </Form>
          </Modal>
          <Modal title="删稿说明" visible={this.state.deleteExplainVisible} okText="确定" cancelText="取消" onOk={this.deleteExplainModalOk} onCancel={this.deleteExplainModalCancle}>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item>
                {getFieldDecorator("singleDeleteNote", {
                  rules: [
                    { required: true, message: "请输入推稿说明!" },
                    { whitespace: true, message: "不能输入空字符!" },
                    { max: 300, message: "不能大于300个字符" }
                  ]
                })(<TextArea placeholder="请输入300字以内的说明。。。" allowClear rows={6} />)}
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </QueueAnim>
    );
  }
}

export default List;
